<?php
use Think\Log;
//打印数据内容
function file2dir($sourcefile, $dir,$filename){
    if(! file_exists($sourcefile)){
        return false;
    }
    //$filename = basename($sourcefile);
    return copy($sourcefile, $dir .''. $filename);
}

function sfp($array){
	dump($array, TRUE, '<pre>', FALSE);
}

//对像转化成数据
function object_to_array($obj){
	if(empty($obj)) return ($arr=array());
	$_arr = is_object($obj) ? get_object_vars($obj) :$obj;
	foreach ($_arr as $key=>$val){
		$val = (is_array($val) || is_object($val)) ? object_to_array($val):$val;
		$arr[$key] = $val;
	}
	return $arr;
}

//向指定的URL用POST方法发送数据，只在调用发短信接口时用
function http_post_data($url, $text){
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $text);
	ob_start();
	curl_exec($ch);
	$content = ob_get_contents();
	ob_end_clean();
	$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	Log::record('Post url-->'.$url, Log::DEBUG);
	Log::record('Request text-->:'.$text, Log::DEBUG);
	Log::record('Reponse status-->'.$status, Log::DEBUG);
	Log::record('Reponse text-->'.$content, Log::DEBUG);
	log::save();
	return $content;
}

// $data is array or object
function trans_post_data($data){
	$result = '';
	if(is_array($data)){
		foreach ($data as $key => $value){
			$result = $result.$key.'='.urlencode($value).'&';
		}
		if(!empty($result)){
			$result = substr($result, 0, strlen($result)-1);
		}
	}else if(is_object($data)){
		$data = object_to_array($data);
		return trans_post_data($data);
	}else{
		$result = $data;
	}
	return $result;
}

/*
 *$url: destination url address
 *$json: content of json
 */
function http_post_json($url, $json) {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' .strlen($json))
        );
        curl_setopt($ch, CURLOPT_TIMEOUT, 12);
        set_time_limit(120);
        ob_start();
        curl_exec($ch);
        $content = ob_get_contents();
        ob_end_clean();
        $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        Log::record('Post url-->'.$url, Log::DEBUG);
        Log::record('Request json-->:'.$json, Log::DEBUG);
        Log::record('Reponse status-->'.$status, Log::DEBUG);
        Log::record('Reponse json-->'.$content, Log::DEBUG);
        log::save();
        return $content;


}

//写日志公用函数
function write_log($title, $msg, $level=Log::DEBUG){
	if (is_object($msg)){
		$log = print_r(object_to_array($msg), true);
	}elseif (is_array($msg)){
		$log = print_r($msg, true);
	}else{
		$log = strval($msg);
	}
	Log::record($title.': '.$log, $level);
	log::save();
}

//微信回调写日志函数
function LogWechat($msg){
	return write_log('LogWechat', $msg, Log::DEBUG);
}

//支持中文，解决中文乱码问题，入参为 array $param
function generate_json($param){
	foreach ( $param as $key => $value ) {
	    if(is_object($value)){
	        $value = object_to_array($value);
	    }
	    if(is_array($value)){
	        $value = generate_json($value);
	    }
		$param[$key] =  urlencode( $value );
	}
	$param = urldecode(json_encode ($param));
	return $param;
}

// 以下为XML解析处理
function xml_decode($xml, $root = 'root') {
	$search = '/<(' . $root . ')>(.*)<\/\s*?\\1\s*?>/s';
	$array = array ();
	if(preg_match($search, $xml, $matches)){
		$array = xml_to_array($matches[2]);
	}
	return $array;
}

function xml_to_array($xml) {
	$search = '/<(\w+)\s*?(?:[^\/>]*)\s*(?:\/>|>(.*?)<\/\s*?\\1\s*?>)/s';
	$array = array ();
	if(preg_match_all($search, $xml, $matches)){
		foreach ($matches[1] as $i => $key) {
			$value = $matches[2][$i];
			if(preg_match_all($search, $value, $_matches)){
				$array[$key] = xml_to_array($value);
			}else{
				if('ITEM' == strtoupper($key)){
					$array[] = html_entity_decode($value);
				}else{
					$array[$key] = html_entity_decode($value);
				}
			}
		}
	}
	return $array;
}

/* 按参数$param值作为KEY，取$data数组的子集
 * mixed $param: array(多个参数), string(单个参数)
 * return: array
 * */
function getCondition($param, $data){
	$arr = array();
	if(is_array($param)){
		foreach ($param as $key => $value){
			$arr = array_merge($arr, array($value=>$data[$value]));
		}
	}else{
		$arr = array($param => $data[$param]);
	}
	return $arr;
}

/* 按参数$param值作为KEY，取$data数组的子集，value值非empty
 * mixed $param: array(多个参数), string(单个参数)
 * return: array
 * */
function getConditionExceptEmpty($data, $param=null){
	$arr = array();
	if(is_array($param)){
		foreach ($param as $key => $value){
			if(isset($data[$value]) && !empty($data[$value])){
				$arr = array_merge($arr, array($value=>$data[$value]));
			}
		}
	}elseif(is_string($param)){
		if(isset($data[$param]) && !empty($data[$param])){
			$arr = array($param => $data[$param]);
		}
	}else{
		$arr = array_filter($data);
	}
	return $arr;
}

/* 按参数$param值作为KEY，从$data数组中去除这些键值对
 * mixed $param: array(多个参数), string(单个参数)
 * return: array
 * */
function exceptArray($param, $data){
	if(is_array($param)){
		foreach ($param as $key => $value){
			unset($data[$value]);
		}
	}else{
		unset($data[$param]);
	}
	return $data;
}

function dealArray($data, $key, $prefix, $num){
	if(is_array($data)){
		foreach ($data as $k => $value){
			if(isset($value[$key])){
				$data[$k][$key] = jointStringByTimes($prefix, $num).$value[$key];
			}
		}
	}else{
		$data = jointStringByTimes($prefix, $num).$data;
	}
	return $data;
}

function jointStringByTimes($prefix, $num){
	$str = '';
	$num = intval($num);
	for ($i=0; $i<$num; $i++){
		$str .= strval($prefix);
	}
	return $str;
}

function getWebSiteUrl(){
	return "http://".$_SERVER['HTTP_HOST'];
}

function getRelativePath($model=''){
	$scriptname = $_SERVER['SCRIPT_NAME'];
	if(!empty($model)){
		$scriptname = $scriptname."/".$model;
	}
	return $scriptname;
}

function getDateString($time=null){
	if(is_numeric($time)){
		return date('Y-m-d', $time);
	}else
	if(is_string($time) && strlen($time) >= 10){
		return substr($time, 0, 10);
	}else{
		return  date('Y-m-d', time());
	}	
}

function safe_replace($string) {
    $string = trim($string);
    $string = str_replace(array('\\',';','\'','%2527','%27','%20','&', '"', '<', '>'), array('','','','','','','&amp;', '&quot;', '&lt;', '&gt;'), $string);
    $string=nl2br($string);
    return $string;
}

function get_safe_replace($array){
    if(!is_array($array)) return safe_replace(strip_tags($array));
    foreach($array as $k => $val) $array[$k] = get_safe_replace($val);
    return $array;
}


function get_title_brief($string){
    if(strlen($string)>20) $string=mb_substr($string,0,18,"utf-8") . '...';
    return $string;
}
function get_content_brief($string){
    if(strlen($string)>40) $string=mb_substr($string,0,38,"utf-8") . '...';
    return $string;
}

function getTimeNow($onlyDate=false){
    if($onlyDate){
        return date('Y-m-d', time());
    }else{
        return date('Y-m-d H:i:s', time());
    }
}

function getYearNow(){
	return date('Y', time());
}

function getMonthNow(){
	return strval(intval(date('m', time())));
}

// 只返回日期部分
function splitDateString($datetime){
	if(!empty($datetime)){
		$date = explode(" ", $datetime, 2);
		$date = empty($date)? $datetime :$date[0];
	}else {
		$date = $datetime;
	}
	return $date;
}

//获取某月的天数
function getDaysByYearAndMonth($year, $month){
	//首先判断闰年
	$year = intval($year);
	if($year%400 == 0  || ($year%4 == 0 && $year%100 !== 0)){
		$rday = 29;
	}else{
		$rday = 28;
	}
	$month = intval($month);
	if($month == 2){
		return $rday;
	}else{
		//判断是大月（31），还是小月（30）
		return (($month - 1)%7%2) ? 30 : 31;
	}
}

//$offset 偏移月数；$offset=FALSE时返回月末最后一月的日期
function getDateByMonthOffset($offset, $firstday=FALSE){
	$year = getYearNow()+ intval(intval($offset)/12);
	$month = getMonthNow() + intval($offset)%12;
	$day = $firstday? 1: getDaysByYearAndMonth($year, $month);
	return (strval($year).'-'.$month.'-'.$day);
}

// $showtype: 0 xx/xx   1 x年x月x日	2 x年x月x日x时x分 	3 x年x月x日x时x分x秒  4 xxxx/xx/xx
function formateDateTime($datetime, $showtype=0, $length=null){
	$datetime = trim($datetime);
	if(is_null($length)){
		$length = intval(C('DATETIME_LEN'));
	}
	if(!empty($datetime) && strlen($datetime)===$length){
		switch (intval($showtype)) {
			case 0:{
				$str1 = intval(substr($datetime,5,2));
				$str2 = intval(substr($datetime,8,2));
				$datetime = $str1.'/'.$str2;
			};
			break;
			case 1:{
				$str1 = intval(substr($datetime,5,2));
				$str2 = intval(substr($datetime,8,2));
				$datetime = substr($datetime,0,4).'年'.$str1.'月'.$str2.'日';
			};
			break;
			case 2:{
				$str1 = intval(substr($datetime,5,2));
				$str2 = intval(substr($datetime,8,2));
				$str3 = intval(substr($datetime,11,2));
				$str4 = intval(substr($datetime,14,2));
				$datetime = substr($datetime,0,4).'年'.$str1.'月'.$str2.'日'.$str3.'时'.$str4.'分';
			};
			break;
			case 3:{
				$str1 = intval(substr($datetime,5,2));
				$str2 = intval(substr($datetime,8,2));
				$str3 = intval(substr($datetime,11,2));
				$str4 = intval(substr($datetime,14,2));
				$str5 = intval(substr($datetime,17,2));
				$datetime = substr($datetime,0,4).'年'.$str1.'月'.$str2.'日'.$str3.'时'.$str4.'分'.$str5.'秒';
			};
			break;
			case 4:{
				$str1 = substr($datetime,5,2);
				$str2 = substr($datetime,8,2);
				$datetime = substr($datetime,0,4).'/'.$str1.'/'.$str2.'/';
			};
			break;
			default:
			break;
		}
	}
	return $datetime;
}

//按$param数组，提取参数值
function getValidParameters($param, $isPost=FALSE, $urldecode =FALSE) {
	$result = array ();
	if(is_object($param)){
		$param = object_to_array($param);
	}elseif (is_array($param)){
	}else{
		$param = array($param);
	}
	$data = $isPost ? $_POST : $_REQUEST;
	foreach ( $param as $key => $keyvalue ) {
		if (isset ( $data [$keyvalue] )) {
			$value = $urldecode ? urldecode ( $data [$keyvalue] ) : $data [$keyvalue];
			$result = array_merge ( $result, array (
					$keyvalue => $value
			) );
		}
	}
	return $result;
}

//$param, $data array
function filterJsonParameters($param, $data, $urldecode =FALSE){
	$result = array ();
	if(is_object($param)){
		$param = object_to_array($param);
	}elseif (is_array($param)){
	}else{
		$param = array($param);
	}
	foreach ( $param as $key => $keyvalue ) {
		if (isset ( $data [$keyvalue] )) {
			$value = $urldecode ? urldecode ( $data [$keyvalue] ) : $data [$keyvalue];
			$result = array_merge ( $result, array (
					$keyvalue => $value
			) );
		}
	}
	return $result;
}

/**************************************alipay*****************************************************/
/**
 * 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
 * @param $para 需要拼接的数组
 * return 拼接完成以后的字符串
 */
function createLinkstring($para) {
	$arg  = "";
	while (list ($key, $val) = each ($para)) {
		$arg.=$key."=".$val."&";
	}
	//去掉最后一个&字符
	$arg = substr($arg,0,count($arg)-2);

	//如果存在转义字符，那么去掉转义
	if(get_magic_quotes_gpc()){$arg = stripslashes($arg);}

	return $arg;
}
/**
 * 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串，并对字符串做urlencode编码
 * @param $para 需要拼接的数组
 * return 拼接完成以后的字符串
 */
function createLinkstringUrlencode($para) {
	$arg  = "";
	while (list ($key, $val) = each ($para)) {
		$arg.=$key."=".urlencode($val)."&";
	}
	//去掉最后一个&字符
	$arg = substr($arg,0,count($arg)-2);

	//如果存在转义字符，那么去掉转义
	if(get_magic_quotes_gpc()){$arg = stripslashes($arg);}

	return $arg;
}
/**
 * 除去数组中的空值和签名参数
 * @param $para 签名参数组
 * return 去掉空值与签名参数后的新签名参数组
 */
function paraFilter($para) {
	$para_filter = array();
	while (list ($key, $val) = each ($para)) {
		if($key == "sign" || $key == "sign_type" || $val == "")continue;
		else	$para_filter[$key] = $para[$key];
	}
	return $para_filter;
}
/**
 * 对数组排序
 * @param $para 排序前的数组
 * return 排序后的数组
 */
function argSort($para) {
	ksort($para);
	reset($para);
	return $para;
}

/**
 * 远程获取数据，POST模式
 * 注意：
 * 1.使用Crul需要修改服务器中php.ini文件的设置，找到php_curl.dll去掉前面的";"就行了
 * 2.文件夹中cacert.pem是SSL证书请保证其路径有效，目前默认路径是：getcwd().'\\cacert.pem'
 * @param $url 指定URL完整路径地址
 * @param $cacert_url 指定当前工作目录绝对路径
 * @param $para 请求的数据
 * @param $input_charset 编码格式。默认值：空值
 * return 远程输出的数据
 */
function getHttpResponsePOST($url, $cacert_url, $para, $input_charset = '') {
	if (trim($input_charset) != '') {
		$url = $url."_input_charset=".$input_charset;
	}
	write_log('REQUEST', $url);
	$curl = curl_init($url);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);//SSL证书认证
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//严格认证
	curl_setopt($curl, CURLOPT_CAINFO,$cacert_url);//证书地址
	curl_setopt($curl, CURLOPT_HEADER, 0 ); // 过滤HTTP头
	curl_setopt($curl,CURLOPT_RETURNTRANSFER, 1);// 显示输出结果
	curl_setopt($curl,CURLOPT_POST,true); // post传输数据
	curl_setopt($curl,CURLOPT_POSTFIELDS,$para);// post传输数据
	$responseText = curl_exec($curl);
	//var_dump( curl_error($curl) );//如果执行curl过程中出现异常，可打开此开关，以便查看异常内容
	curl_close($curl);
	write_log('RESPONSE', $responseText);
	return $responseText;
}

/**
 * 远程获取数据，GET模式
 * 注意：
 * 1.使用Crul需要修改服务器中php.ini文件的设置，找到php_curl.dll去掉前面的";"就行了
 * 2.文件夹中cacert.pem是SSL证书请保证其路径有效，目前默认路径是：getcwd().'\\cacert.pem'
 * @param $url 指定URL完整路径地址
 * @param $cacert_url 指定当前工作目录绝对路径
 * return 远程输出的数据
 */
function getHttpResponseGET($url,$cacert_url) {
	$curl = curl_init($url);
	curl_setopt($curl, CURLOPT_HEADER, 0 ); // 过滤HTTP头
	curl_setopt($curl,CURLOPT_RETURNTRANSFER, 1);// 显示输出结果
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);//SSL证书认证
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//严格认证
	curl_setopt($curl, CURLOPT_CAINFO,$cacert_url);//证书地址
	$responseText = curl_exec($curl);
	//var_dump( curl_error($curl) );//如果执行curl过程中出现异常，可打开此开关，以便查看异常内容
	curl_close($curl);

	return $responseText;
}

/**
 * 实现多种字符编码方式
 * @param $input 需要编码的字符串
 * @param $_output_charset 输出的编码格式
 * @param $_input_charset 输入的编码格式
 * return 编码后的字符串
 */
function charsetEncode($input,$_output_charset ,$_input_charset) {
	$output = "";
	if(!isset($_output_charset) )$_output_charset  = $_input_charset;
	if($_input_charset == $_output_charset || $input ==null ) {
		$output = $input;
	} elseif (function_exists("mb_convert_encoding")) {
		$output = mb_convert_encoding($input,$_output_charset,$_input_charset);
	} elseif(function_exists("iconv")) {
		$output = iconv($_input_charset,$_output_charset,$input);
	} else die("sorry, you have no libs support for charset change.");
	return $output;
}
/**
 * 实现多种字符解码方式
 * @param $input 需要解码的字符串
 * @param $_output_charset 输出的解码格式
 * @param $_input_charset 输入的解码格式
 * return 解码后的字符串
 */
function charsetDecode($input,$_input_charset ,$_output_charset) {
	$output = "";
	if(!isset($_input_charset) )$_input_charset  = $_input_charset ;
	if($_input_charset == $_output_charset || $input ==null ) {
		$output = $input;
	} elseif (function_exists("mb_convert_encoding")) {
		$output = mb_convert_encoding($input,$_output_charset,$_input_charset);
	} elseif(function_exists("iconv")) {
		$output = iconv($_input_charset,$_output_charset,$input);
	} else die("sorry, you have no libs support for charset changes.");
	return $output;
}

/**
 * 签名字符串
 * @param $prestr 需要签名的字符串
 * @param $key 私钥
 * return 签名结果
 */
function md5Sign($prestr, $key) {
	$prestr = $prestr . $key;
	return md5($prestr);
}

/**
 * 验证签名
 * @param $prestr 需要签名的字符串
 * @param $sign 签名结果
 * @param $key 私钥
 * return 签名结果
 */
function md5Verify($prestr, $sign, $key) {
	$prestr = $prestr.$key;
	$mysgin = md5($prestr);
	return($mysgin == $sign);
}

/**
 * 签名字符串
 * @param $prestr 需要签名的字符串
 * return 签名结果
 */
function rsaSign($prestr) {
	$public_key= file_get_contents('./Public/alipay/rsa_private_key.pem');
	$pkeyid = openssl_get_privatekey($public_key);
	openssl_sign($prestr, $sign, $pkeyid);
	openssl_free_key($pkeyid);
	$sign = base64_encode($sign);
	return $sign;
}

/**
 * 验证签名
 * @param $prestr 需要签名的字符串
 * @param $sign 签名结果
 * return 签名结果
*/
function rsaVerify($prestr, $sign) {
     $sign = base64_decode($sign);
     $public_key= file_get_contents('./Public/alipay/alipay_public_key.pem');
     $pkeyid = openssl_get_publickey($public_key);
     if ($pkeyid) {
         $verify = openssl_verify($prestr, $sign, $pkeyid);
         openssl_free_key($pkeyid);
     }
     return($verify == 1);
}

/**
 * 设置用户缓存，暂存在session中
 * $value mixed，$name对应的值，当$name为空时，设置整个session
 * $name string
 * return null
 */
function setUserCache($value,$name='',$isApi=TRUE){
	if($isApi){
		$parent = 'NORMAL_USER';
	}else{
		$parent = 'MANAGE_USER';
	}
	if (empty($name)){
		session($parent, $value);
	}else{
		$arr = session($parent);
		$arr[$name] = $value;
		session($parent, $arr);
	}
}
/**
 * 查询用户缓存，暂存在session中
 * $name string，$name对应的值，当$name为空时，返回整个数组
 * return mixed
 */
function getUserCache($name='',$isApi=TRUE){
	if($isApi){
		$parent = 'NORMAL_USER';
	}else{
		$parent = 'MANAGE_USER';
	}
	if (empty($name)){
		return session($parent);
	}else{
		$arr = session($parent);
		return $arr[$name];
	}
}
//移除缓存或其中的某一项
function removeUserCache($name='',$isApi=TRUE){
	if($isApi){
		$parent = 'NORMAL_USER';
	}else{
		$parent = 'MANAGE_USER';
	}
	if (empty($name)){
		return session($parent, null);
	}else{
		$arr = session($parent);
		unset($arr[$name]);
		return session($parent, $arr);
	}
}

function setManageCache($value,$name=''){
	return setUserCache($value,$name,FALSE);
}

function getManageCache($name=''){
	return getUserCache($name,FALSE);
}

function removeManageCache($name=''){
	return removeUserCache($name,FALSE);
}

